package com.leboncoin.html;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.leboncoin.bean.ClassifiedBean;

public class LeboncoinHtmlClassifiedDetail {

	static Logger logger = Logger.getLogger(LeboncoinHtmlClassifiedDetail.class.getName());	
	Document document;
	
	public LeboncoinHtmlClassifiedDetail(String htmlSource) {
		super();
		this.document = Jsoup.parse(htmlSource);		
	}

	public Boolean populateImages(ClassifiedBean classifiedBean){

		Boolean isImage = false;
		String searchAttribute = "style";
		String searchAttributeValue = "background-image";
		
		// Image
		if (document != null) {
			Elements imageDivs = document.getElementsByAttributeValueContaining(searchAttribute, searchAttributeValue);
			
			List<String> imageLinks = new ArrayList<String>();
			for (Iterator iterator = imageDivs.iterator(); iterator.hasNext();) {
				Element imageDiv = (Element) iterator.next();
				
				String bgImageStyle = imageDiv.attr("style");
				String url = bgImageStyle.substring(bgImageStyle.indexOf("http"), bgImageStyle.indexOf("jpg")+3);
				imageLinks.add(url);
			} 
			classifiedBean.setImageLinks(imageLinks);
		} 
		
		return isImage;
	}
	
	public Boolean populatePrice(ClassifiedBean classifiedBean){
		
		Boolean isPrice = false;
		
		if (document != null) {
			Elements search = document.select("span[class=price]");
			for (Element span:search){
				String priceString =span.text();
				try {
					priceString = priceString.substring(0, priceString.indexOf("€")-1);
					priceString = priceString.replaceAll("\\s", "");
				}catch (Exception e){
					logger.severe("Cannot convert price string to number: "+priceString);
					break;
				}
				try {
					Float price = Float.parseFloat(priceString);
					classifiedBean.setPrice(price);
					isPrice = true;
				} catch(NumberFormatException e){
					logger.severe("Cannot convert price string to number: "+priceString);
					break;
				}
			}		
		} else {
			logger.severe("Cannot get span[class=price] from page ");
		}
		
		return isPrice;
	}

}
